package com.hxkcloud.patient.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hxkcloud.patient.R;
import com.hxkcloud.patient.adapter.AssessRecordAdapter;
import com.hxkcloud.patient.beans.AssessRecordBean;
import com.hxkcloud.patient.beans.AssessRecordWholeBean;
import com.hxkcloud.patient.beans.resultbeans.BaseResultBean;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.views.pulltorefreshlayout.PullToRefreshLayout;
import com.hxkcloud.patient.views.pulltorefreshlayout.PullableRecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by william_sun on 2016-07-07.
 * Description:评估记录列表页
 */
public class AssessRecordListActivity extends BaseActivity implements View.OnClickListener, PullToRefreshLayout.OnRefreshListener, AssessRecordAdapter.itemClickListener, AssessRecordAdapter.ResultSelectedListener {
    //title
    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;
    private TextView tv_del;


    private PullToRefreshLayout refreshLayout;
    private PullableRecyclerView recycleView;

    private AssessRecordWholeBean wholeBean;
    private int totalCount = 0;
    private List<AssessRecordBean> records;
    private AssessRecordAdapter adapter;

    private int pageIndex = 1;
    private int pageSize = 15;
    private int loadmoreType = 0;//0第一次获取1刷新2更多

    private String patientId;
    private String patientName;

    private LinearLayout scaleLayout;
    private TextView scaleTV;
    private View scaleView;

    private LinearLayout questionLayout;
    private TextView questionTV;
    private View questionView;


    private View bottomView;
    private LinearLayout bottomLayout;

    private boolean isAllSelect = false;
    private Button allselectBtn;

    private String scaletype = "1";//量表
    private String questiontype = "2";//问卷

    private boolean isquestion = false;
    private boolean isDel = true;

    private BaseResultBean delResultBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_assessrecordlist);

        patientId = this.getIntent().getStringExtra("patientId");
        patientName = this.getIntent().getStringExtra("patientName");
        records = new ArrayList<>();

        initView();
        initData();
        initListener();
    }

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_GETASSESSRECORD_SUCCESS:
                if (loadmoreType == 1) {
                    refreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                    records.clear();
                } else if (loadmoreType == 2) {
                    refreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                }
                if (msg.obj != null) {
                    wholeBean = (AssessRecordWholeBean) msg.obj;
                    totalCount = wholeBean.getTotalCount();
                    if (wholeBean.getList() != null && wholeBean.getList().size() > 0) {
                        records.addAll(wholeBean.getList());
                        if (isDel) {
                            if (records != null && records.size() > 0) {
                                for (int i = 0; i < records.size(); i++) {
                                    records.get(i).setIsDisplay(false);
                                }
                            }
                        } else {
                            if (records != null && records.size() > 0) {
                                for (int i = 0; i < records.size(); i++) {
                                    records.get(i).setIsDisplay(true);
                                }
                            }
                        }

                    }
                } else {
                    toastMsg(R.string.datagetfail);
                }
                adapter.setData(records);
                break;
            case MessageCode.NETWORKCODE_GETASSESSRECORD_FAILURE:
                if (loadmoreType == 1) {
                    refreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
                } else if (loadmoreType == 2) {
                    refreshLayout.loadmoreFinish(PullToRefreshLayout.FAIL);
                }
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(R.string.datagetfail);
                }
                adapter.setData(records);
                break;
            case MessageCode.NETWORKCODE_DELETEUSERQUESTION_SUCCESS:
                if (msg.obj != null) {
                    delResultBean = (BaseResultBean) msg.obj;
                    toastMsg(delResultBean.getMessage());
                    loading();
                    records.clear();
                    bottomLayout.setVisibility(View.GONE);
                    bottomView.setVisibility(View.GONE);
                    if (isquestion) {
                        YiJiaHuNetWorkUtils.getAssessRecord(patientId, questiontype, pageIndex, pageSize, handler);
                    } else {
                        YiJiaHuNetWorkUtils.getAssessRecord(patientId, scaletype, pageIndex, pageSize, handler);
                    }

                }

                break;
            case MessageCode.NETWORKCODE_DELETEUSERQUESTION_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(R.string.datagetfail);
                }
                break;
            case MessageCode.NETWORKCODE_CONNECT_ERROR:
                if (loadmoreType == 1) {
                    refreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
                } else if (loadmoreType == 2) {
                    refreshLayout.loadmoreFinish(PullToRefreshLayout.FAIL);
                }
                break;
        }
    }

    @Override
    protected void initView() {
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);
        tv_del = (TextView) findViewById(R.id.tv_title_func);

        refreshLayout = (PullToRefreshLayout) findViewById(R.id.refreshlayout_assessrecordlist);
        recycleView = (PullableRecyclerView) findViewById(R.id.recyclerview_assessrecordlist);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(this);
        tv_title.setText(getResources().getText(R.string.assessrecord));
        tv_del.setVisibility(View.VISIBLE);
        tv_del.setText(getResources().getText(R.string.delete));
        tv_del.setOnClickListener(this);

        scaleLayout = (LinearLayout) findViewById(R.id.assessrecordlist_layout_scale);
        scaleTV = (TextView) findViewById(R.id.assessrecordlist_tv_scale);
        scaleView = (View) findViewById(R.id.assessrecordlist_view_scale);

        questionLayout = (LinearLayout) findViewById(R.id.assessrecordlist_layout_question);
        questionTV = (TextView) findViewById(R.id.assessrecordlist_tv_question);
        questionView = (View) findViewById(R.id.assessrecordlist_view_question);

        bottomView = (View) findViewById(R.id.assessrecordlist_view_bottom);
        bottomLayout = (LinearLayout) findViewById(R.id.assessrecordlist_layout_bottom);
        allselectBtn = (Button) findViewById(R.id.assessrecordlist_btn_allselect);

        LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleView.setLayoutManager(mLayoutManager);
        refreshLayout.setOnRefreshListener(this);

        adapter = new AssessRecordAdapter(mContext, records, this, this);
        recycleView.setAdapter(adapter);
    }

    @Override
    protected void initListener() {
        scaleLayout.setOnClickListener(this);
        questionLayout.setOnClickListener(this);
        allselectBtn.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        loading();
        YiJiaHuNetWorkUtils.getAssessRecord(patientId, scaletype, pageIndex, pageSize, handler);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                if (!isDel) {
                    isDel = true;
                    tv_del.setText(getResources().getText(R.string.delete));
                    bottomLayout.setVisibility(View.GONE);
                    bottomView.setVisibility(View.GONE);
                    if (records != null && records.size() > 0) {
                        for (int i = 0; i < records.size(); i++) {
                            records.get(i).setIsDisplay(false);
                        }
                    }
                    adapter.notifyDataSetChanged();
                    return;
                }
                finish();
                break;
            case R.id.assessrecordlist_layout_scale:
                isAllSelect = false;
                allselectBtn.setBackgroundResource(R.mipmap.btn_multiselect);

                isquestion = false;
//                bottomLayout.setVisibility(View.GONE);
//                bottomView.setVisibility(View.GONE);
                scaleTV.setTextColor(getResources().getColor(R.color.light_blue));
                scaleView.setVisibility(View.VISIBLE);
                questionTV.setTextColor(getResources().getColor(R.color.grey_text1));
                questionView.setVisibility(View.INVISIBLE);
//                isDel = true;
                if(isDel){
                    tv_del.setText(getResources().getText(R.string.delete));
                }else{
                    tv_del.setText(getResources().getText(R.string.data_sure));
                }
                records.clear();
                loading();
                pageIndex = 1;
                YiJiaHuNetWorkUtils.getAssessRecord(patientId, scaletype, pageIndex, pageSize, handler);
                break;
            case R.id.assessrecordlist_layout_question:
                isAllSelect = false;
                allselectBtn.setBackgroundResource(R.mipmap.btn_multiselect);

                isquestion = true;
//                bottomLayout.setVisibility(View.GONE);
//                bottomView.setVisibility(View.GONE);
                scaleTV.setTextColor(getResources().getColor(R.color.grey_text1));
                scaleView.setVisibility(View.INVISIBLE);
                questionTV.setTextColor(getResources().getColor(R.color.light_blue));
                questionView.setVisibility(View.VISIBLE);
//                isDel = true;
                if(isDel){
                    tv_del.setText(getResources().getText(R.string.delete));
                }else{
                    tv_del.setText(getResources().getText(R.string.data_sure));
                }


                records.clear();
                loading();
                pageIndex = 1;
                YiJiaHuNetWorkUtils.getAssessRecord(patientId, questiontype, pageIndex, pageSize, handler);
                break;
            case R.id.tv_title_func:
                if (isDel) {
                    isDel = false;

                    bottomLayout.setVisibility(View.VISIBLE);
                    bottomView.setVisibility(View.VISIBLE);
                    tv_del.setText(getResources().getText(R.string.data_sure));
                    if (records != null && records.size() > 0) {
                        for (int i = 0; i < records.size(); i++) {
                            records.get(i).setIsDisplay(true);
                        }
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    String userQuestionId = "";
                    StringBuffer stringBuffer = new StringBuffer();
                    if (records != null && records.size() > 0) {
                        for (int i = 0; i < records.size(); i++) {
                            if (records.get(i).isSelect()) {
                                stringBuffer.append(records.get(i).getAnswerId());
                                stringBuffer.append(",");
                            }
                        }
                        String s = stringBuffer.toString();
                        if (TextUtils.isEmpty(s)) {
//                            isDel = true;
//                            tv_del.setText(getResources().getText(R.string.delete));
//                            bottomLayout.setVisibility(View.GONE);
//                            bottomView.setVisibility(View.GONE);
//                            if (records != null && records.size() > 0) {
//                                for (int i = 0; i < records.size(); i++) {
//                                    records.get(i).setIsDisplay(false);
//                                }
//                            }
//                            adapter.notifyDataSetChanged();
                            toastMsg(getResources().getString(R.string.select_deleteitem));
                            return;
                        } else {
                            userQuestionId = s.substring(0, s.length() - 1);
                        }
                    } else {
//                        toastMsg(getResources().getString(R.string.select_deleteitem));
                        isDel = true;
                        tv_del.setText(getResources().getText(R.string.delete));
                        bottomLayout.setVisibility(View.GONE);
                        bottomView.setVisibility(View.GONE);
                        if (records != null && records.size() > 0) {
                            for (int i = 0; i < records.size(); i++) {
                                records.get(i).setIsDisplay(false);
                            }
                        }
                        adapter.notifyDataSetChanged();
                        return;
                    }

                    isDel = true;
                    tv_del.setText(getResources().getText(R.string.delete));

                    YiJiaHuNetWorkUtils.delUserQuestion(userQuestionId, handler);
                    //删除接口
                }


                break;
            case R.id.assessrecordlist_btn_allselect://全选

                if (isAllSelect) {
                    allselectBtn.setBackgroundResource(R.mipmap.btn_multiselect);
                    for (int i = 0; i < records.size(); i++) {
                        records.get(i).setIsSelect(false);
                    }
                    isAllSelect = false;
                } else {
                    allselectBtn.setBackgroundResource(R.mipmap.btn_multiselect_pre);
                    for (int i = 0; i < records.size(); i++) {
                        records.get(i).setIsSelect(true);
                    }
                    isAllSelect = true;
                }
                adapter.notifyDataSetChanged();


                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (!isDel) {
            isDel = true;
            tv_del.setText(getResources().getText(R.string.delete));
            bottomLayout.setVisibility(View.GONE);
            bottomView.setVisibility(View.GONE);
            if (records != null && records.size() > 0) {
                for (int i = 0; i < records.size(); i++) {
                    records.get(i).setIsDisplay(false);
                }
            }
            adapter.notifyDataSetChanged();
            return;
        } else {
            finish();
        }

    }

    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        loading();
        loadmoreType = 1;
        pageIndex = 1;
        isAllSelect = false;
        allselectBtn.setBackgroundResource(R.mipmap.btn_multiselect);
        if (isquestion) {
            YiJiaHuNetWorkUtils.getAssessRecord(patientId, questiontype, pageIndex, pageSize, handler);
        } else {
            YiJiaHuNetWorkUtils.getAssessRecord(patientId, scaletype, pageIndex, pageSize, handler);
        }

    }

    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        if (totalCount <= records.size()) {
            toastMsg(R.string.nomore);
            refreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
        } else {
            loading();
            isAllSelect = false;
            allselectBtn.setBackgroundResource(R.mipmap.btn_multiselect);
            loadmoreType = 2;
            pageIndex++;
            if (isquestion) {
                YiJiaHuNetWorkUtils.getAssessRecord(patientId, questiontype, pageIndex, pageSize, handler);
            } else {
                YiJiaHuNetWorkUtils.getAssessRecord(patientId, scaletype, pageIndex, pageSize, handler);
            }
        }
    }

    @Override
    public void onSelected(String type, int position) {
        if ("select".equals(type)) {
            records.get(position).setIsSelect(true);
            adapter.notifyItemChanged(position);

            boolean isAllSelectS = true;
            for (AssessRecordBean record : records) {
                if (!record.isSelect()) {
                    isAllSelectS = false;
                }
            }

            if (isAllSelectS) {
                allselectBtn.setBackgroundResource(R.mipmap.btn_multiselect_pre);
                isAllSelect = true;
            }
        } else if ("no_select".equals(type)) {
            records.get(position).setIsSelect(false);
            adapter.notifyItemChanged(position);

            boolean isAllSelectNoS = false;
            for (AssessRecordBean record : records) {
                if (!record.isSelect()) {
                    isAllSelectNoS = true;
                }
            }

            if (isAllSelectNoS) {
                allselectBtn.setBackgroundResource(R.mipmap.btn_multiselect);
                isAllSelect = false;
            }
        }
    }

    @Override
    public void onItemClick(int position) {
        Intent iItem = new Intent(mContext, AssessFeedbackActivity.class);
        iItem.putExtra("assessId", records.get(position).getItemId());
        iItem.putExtra("patientId", patientId);
        iItem.putExtra("questionUserId", records.get(position).getAnswerId());
        iItem.putExtra("isFromRecordList", "true");
        startActivity(iItem);
    }
}
